package com.example.asd.puzzle;

import android.app.Service;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;

import org.json.JSONObject;
import org.json.JSONTokener;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

public class PushService extends Service {
    private String TAG="TAG",str_server,str_nick;
    private MyBinder myBinder=new MyBinder();
    private OnMsgReceivedListener listener;
    private boolean runningFlag=true;

    public PushService() {
        str_nick=MainActivity.str_nick;
        str_server=MainActivity.str_server;
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Socket socket = new Socket(str_server,9090);
                    PrintWriter pw=new PrintWriter(socket.getOutputStream());
                    BufferedReader br=new BufferedReader(new InputStreamReader(socket.getInputStream()));
                    JSONObject jsonObject=new JSONObject();
                    jsonObject.put("State","connected");
                    jsonObject.put("Me",str_nick);
                    pw.println(jsonObject.toString());
                    pw.flush();
                    String str;
                    while (runningFlag&&(str=br.readLine())!=null){
                        JSONObject object=(JSONObject)(new JSONTokener(str).nextValue());
                        Log.d(TAG, "run: JSONObject = "+object.toString());
                        if (listener!=null)
                            listener.onMsgReceived(object);
                    }
                }catch (Exception e){
                    e.printStackTrace();
                    if (listener!=null)
                        listener.toastMe(e.toString());
                }
            }
        }).start();
    }

    @Override
    public IBinder onBind(Intent intent) {
        return myBinder;
    }
    public class MyBinder extends Binder{
        public void setListener(OnMsgReceivedListener msgReceivedListener){
            listener=msgReceivedListener;
        }
        public void setRunningFlag(boolean f){
            runningFlag=f;
        }
    }

    @Override
    public boolean onUnbind(Intent intent) {
        super.onUnbind(intent);
        listener=null;
        return true;
    }
}
